import { Button, Progress, message, List, Avatar, Tag } from "antd";
import { DrawerForm } from "@ant-design/pro-components";
import { useState, useEffect } from "react";
import { UploadOutlined, FolderOutlined } from "@ant-design/icons";
import {
  processFolder,
  serverFoldersList,
} from "@/services/api/api-intelligent-processing";

interface LocalUploadProps {
  onClose: () => void;
}

const PAGE_SIZE = 10;

const LocalUpload = ({ onClose }: LocalUploadProps) => {
  const [open, setOpen] = useState(false);
  const [creating, setCreating] = useState(false);
  const [progress, setProgress] = useState(0);
  const [selectedFolder, setSelectedFolder] = useState<string | null>(null);
  const [mediaFiles, setMediaFiles] = useState<ProcessingData.filesList[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: PAGE_SIZE,
    total: 0,
  });
  const [loading, setLoading] = useState(false);

  // 打开抽屉时获取文件列表
  useEffect(() => {
    if (open) {
      fetchFiles();
    }
  }, [open, pagination.current, pagination.pageSize]); // 监听页码和页数变化

  const fetchFiles = async () => {
    setLoading(true);
    try {
      const response = await serverFoldersList({
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      });

      setMediaFiles(response.data.data);
      setPagination(prev => ({
        ...prev,
        total: response.data.total,
      }));
    } catch (error) {
      message.error("获取文件列表失败");
    } finally {
      setLoading(false);
    }
  };

  // 选择文件夹处理函数
  const handleFolderSelect = (file: ProcessingData.filesList) => {
    if (selectedFolder === file.path) {
      setSelectedFolder(null);
    } else {
      setSelectedFolder(file.path);
      // message.info(`已选择文件夹: ${file.name}`);
    }
  };

  // 处理文件夹
  const handleCreate = async () => {
    if (!selectedFolder) {
      message.error("请先选择一个文件夹");
      return false;
    }

    setCreating(true);
    setProgress(0);

    try {
      const interval = setInterval(() => {
        setProgress((prev) => (prev >= 90 ? prev : prev + 10));
      }, 300);

      const res = await processFolder({
        name: selectedFolder,
      });

      clearInterval(interval);
      setProgress(100);
      message.success(res.msg);

      handleDrawerClose(false);

      return true;
    } catch (error) {

      message.error("处理过程中出错");
      return false;
    } finally {
      setCreating(false);
    }
  };

  // 分页变化处理
  const handlePaginationChange = (page: number, pageSize?: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize: pageSize || prev.pageSize,
    }));
  };

  // 关闭抽屉处理
  const handleDrawerClose = (open: boolean) => {
    if (!open) {
      setSelectedFolder(null);
      setProgress(0);
      setCreating(false);
      setPagination({
        current: 1,
        pageSize: PAGE_SIZE,
        total: 0,
      });
      onClose();
    }
    setOpen(open);
  };

  return (
    <DrawerForm
      title="处理媒体文件"
      width={800}
      open={open}
      onOpenChange={handleDrawerClose}
      trigger={
        <Button type="primary" icon={<UploadOutlined />}>
          处理媒体文件
        </Button>
      }
      onFinish={handleCreate}
      submitter={{
        render: (props, defaultDoms) => [
          <Button key="cancel" onClick={() => handleDrawerClose(false)}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={creating}
            onClick={() => props.submit()}
            disabled={!selectedFolder}
          >
            {selectedFolder ? `处理选中的文件夹` : "请先选择文件夹"}
          </Button>,
        ],
      }}
    >
      <div style={{ marginBottom: 24 }}>
        <Button
          icon={<FolderOutlined />}
          onClick={() => fetchFiles()}
          type="default"
          size="large"
        >
          刷新文件列表
        </Button>

        {selectedFolder && (
          <div style={{ marginTop: 16 }}>
            <Tag color="blue" style={{ fontSize: 14, padding: 8 }}>
              当前选中: {mediaFiles.find((f) => f.path === selectedFolder)?.name}
            </Tag>
          </div>
        )}
      </div>

      <div style={{ marginBottom: 24 }}>
        <h4>文件夹列表</h4>
        <List
          size="small"
          bordered
          loading={loading}
          dataSource={mediaFiles}
          renderItem={(file) => (
            <List.Item
              onClick={() => handleFolderSelect(file)}
              style={{
                cursor: "pointer",
                backgroundColor:
                  selectedFolder === file.path ? "#e6f7ff" : "inherit",
              }}
            >
              <List.Item.Meta
                avatar={
                  <Avatar
                    icon={<FolderOutlined />}
                    style={{ backgroundColor: "#faad14" }}
                  />
                }
                title={file.name}
                description="文件夹"
              />
              {selectedFolder === file.path && <Tag color="green">已选中</Tag>}
            </List.Item>
          )}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            onChange: handlePaginationChange,
            onShowSizeChange: (current, size) => handlePaginationChange(1, size),
            showSizeChanger: true,
            pageSizeOptions: ["10", "20", "50", "100"],
            showTotal: (total) => `共 ${total} 条`,
          }}
        />
      </div>

      {creating && (
        <div style={{ marginTop: 24 }}>
          <Progress percent={progress} status="active" />
          <div style={{ textAlign: "center", marginTop: 8 }}>
            正在处理文件夹...
          </div>
        </div>
      )}
    </DrawerForm>
  );
};

export default LocalUpload;
